/*
 * @Author: mrZhang
 * @Date: 2021-08-26 15:16:01
 * @Last Modified by:  mrZhang
 * @Last Modified time: 2021-11-29 13:56:39
 * @Description: 通用图片上传组件
 */

<template>
  <div class="upload">
    <el-upload
      ref="upload"
      :action="uploadUrl"
      :headers="headers"
      list-type="picture-card"
      :name="name"
      class="upload-image"
      :disabled="disabled"
      :class="{ 'hide-upload': hideUpload }"
      :limit="limit"
      :multiple="multiple"
      :show-file-list="showFileList"
      :file-list="fileList"
      :accept="accept"
      :before-upload="beforeUpload"
      :on-change="handleChange"
      :on-preview="handlePictureCardPreview"
      :before-remove="beforeRemove"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
    >
      <div class="upload-tip">
        <i class="el-icon-plus" />
        <div v-if="description" class="el-upload__tip">
          {{ description }}
        </div>
      </div>
    </el-upload>
    <!-- 预览图片 -->
    <el-dialog :visible.sync="dialogVisibleimg" class="uploadDiaglog" append-to-body>
      <div style="width:100%; text-align:center">
        <img width="80%" :src="imgUrlReplace(dialogImageUrl)" alt="">
      </div>
    </el-dialog>
  </div>
</template>

<script>
import urlConfig from '@/urlConfig'
const baseurl = urlConfig.baseURL
import imageMixin from '@/mixins/ImageMixin'
import { getToken } from '@/utils/auth'

export default {
  name: 'UploadFile',
  mixins: [imageMixin],
  props: {
    // v-model 绑定的值
    value: {
      type: [String, Array],
      default: () => ''
    },
    // 是否支持多选
    multiple: {
      type: Boolean,
      default: false
    },
    // 设定文件域的字段名
    name: {
      type: String,
      default: () => 'file'
    },
    // 是否显示已上传文件列表
    showFileList: {
      type: Boolean,
      default: () => true
    },
    // 最大允许上传个数
    limit: {
      type: Number,
      default: () => 5
    },
    // 接受上传的文件类型
    accept: {
      type: String,
      default: () => 'image/jpeg, image/png, image/gif'
    },
    // 文件上传描述
    description: {
      type: String,
      default: () => ''
    },
    // 文件大小限制，单位KB，默认5MB
    size: {
      type: Number,
      default: () => 5 * 1024
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: () => false
    }
  },
  data() {
    return {
      uploadUrl: baseurl + '/api/file/upload',
      dialogVisibleimg: false,
      dialogImageUrl: '',
      fileList: [],

      hideUpload: false,

      headers: { 'Authorization': getToken() }
    }
  },
  watch: {// dd
    value: {
      handler(nval) {
        nval && this.watchValue()
        this.update()
      },
      immediate: true
    },
    disabled: {
      handler(nval) {
        if (nval) { this.hideUpload = nval }
      },
      immediate: true
    }
  },
  mounted() {
    console.log(this.uploadUrl)
  },
  methods: {
    /**
			 * 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
			 */
    handleChange(file, fileList) {
      const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png' || file.raw.type === 'image/gif'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 、png 格式!')
        fileList.splice(-1, 1)// 移除错误文件
        return false
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!')
        fileList.splice(-1, 1)
        return false
      }
    },
    /**
			 * 上传文件之前的钩子
			 */
    beforeUpload(file) {
      const fileMax = file.size / 1024 < this.size
      if (!fileMax) {
        this.$message.error(`上传图片大小不能超过 ${this.renderSize(this.size / 1024)}!`)
      }
      return !!fileMax
    },
    /**
			 * 删除文件之前的钩子
			 */
    beforeRemove(file, fileList) {
      return this.$confirm(`确定删除此图片？`).then(() => {
        // this.$message.success("已移除");
      })
    },
    /**
			 * 删除活动展示照片
			 */
    handleRemove(file, fileList) {
      const fileArray = []
      fileList.forEach(el => {
        fileArray.push(el.url)
      })
      this.$emit('updateImg', fileArray.join(','))
    },
    /**
			 * 照片预览
			 */
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisibleimg = true
    },
    /**
			 * 成功上传
			 */
    handleSuccess(response, file, fileList) {
      console.log('🚀 ~ file: index.vue:191 ~ handleSuccess ~ response:', response)
      file.url = response.url
      this.emitInput(this.value ? this.value + ',' + file.url : file.url)
      this.fileList = fileList
    },
    /**
			 * 监听value值 变化
			 */
    watchValue() {
      let valueArray = []
      if (typeof this.value === 'string' || this.value == null) { valueArray = this.value ? this.value.split(',') : [] } else { valueArray = [...this.value] }
      this.fileList = valueArray.map(item => {
        return { name: item, url: item }
      })
      this.update()
    },
    /**
			 * 更新V-model数据
			 */
    emitInput(value) {
      this.$emit('input', value)
      this.$nextTick(() => {
        this.update()
      })
    },
    /**
			 * 新显示隐藏上传图片按钮
			 */
    update() {
      let valueArray = []
      if (typeof this.value === 'string' || this.value == null) { valueArray = this.value ? this.value.split(',') : [] } else { valueArray = [...this.value] }
      if (valueArray.length >= this.limit) this.hideUpload = true
      else this.hideUpload = false
    }
  }
}
</script>

<style lang="scss" scoped>
	::v-deep .el-upload-list--picture-card {
		display: flex;
		::v-deep .el-upload-list__item {
			margin: 0;
		}
	}
	.hide-upload v::deep .el-upload--picture-card {
		display: none;
	}

	.hide-upload {
		::v-deep .el-upload--picture-card {
			display: none !important;
		}
	}
	.upload-tip {
		height: 100%;
		line-height: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		padding: 10px;
	}
	.el-upload__tip {
		line-height: 20px;
		margin-top: 10px;
	}
</style>
<style >
	.uploadDiaglog .el-dialog {
		margin-top: 5% !important;
	}
</style>
